﻿using Business.BookManagement;
using Business.BookManagement.Dto;
using Business.Models;
using Business.Permissions;
using Business.PurchManagement.Dto;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.VisualBasic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;
using WkHtmlToPdfDotNet;
using XCZ;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace Business.PurchManagement
{
    //[Authorize(BusinessPermissions.Purch.Default)]
    public class PurchAppService : BusinessWorkFlowAppService, IPurchAppService
    {
        private const string FormName = "Purch";
        private IRepository<Purch, Guid> _repository;
        private IRepository<Produce, Guid> _repository1;
        private IRepository<Dstributor, Guid> _repository2;

        public PurchAppService(IRepository<Purch, Guid> repository, IRepository<Produce, Guid> repository1, IRepository<Dstributor, Guid> repository2)
        {
            _repository = repository;

            _repository1 = repository1;
            _repository2 = repository2;
        }
        #region 增删改查基础方法

        public async Task<PurchDto> Get(Guid id)
        {
            var data = await _repository.GetAsync(id);
            var dto = ObjectMapper.Map<Purch, PurchDto>(data);
            return dto;
        }
        public async Task<PagedResultDto<PurchDto>> GetAll(GetPurchInputDto input)
        {
            var query = (await _repository.GetQueryableAsync());
            //单据主题
            query = query.WhereIf(!string.IsNullOrWhiteSpace(input.Theme), a => a.Theme.Contains(input.Theme));

            //单价编号
            query = query.WhereIf(!string.IsNullOrWhiteSpace(input.SerialNumber), a => a.SerialNumber.Contains(input.SerialNumber));

            //关联项目
            query = query.WhereIf(!string.IsNullOrWhiteSpace(input.Markedness), a => a.Markedness.Contains(input.Markedness));

            //添加人员
            query = query.WhereIf(!string.IsNullOrWhiteSpace(input.Personnel), a => a.Personnel.Contains(input.Personnel));

            //日期查询
            query = query.WhereIf(!string.IsNullOrEmpty(input.StartDate), x => x.Enquiry >= DateTime.Parse(input.StartDate));
            query = query.WhereIf(!string.IsNullOrEmpty(input.EndDate), x => x.Enquiry <= DateTime.Parse(input.EndDate).AddDays(1));

            var totalCount = await query.CountAsync();
            var items = await query.OrderBy(input.Sorting ?? "Id")
                        .ToListAsync();



            var dtos = ObjectMapper.Map<List<Purch>, List<PurchDto>>(items);
            return new PagedResultDto<PurchDto>(totalCount, dtos);
        }

        /// <summary>
        /// 连表查询显示
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<PurchDto>> GetAlls(GetPurchInputDto input)
        {
            
            var list = (from a in await _repository.GetQueryableAsync()
                        join b in await _repository1.GetQueryableAsync()
                        on a.Id equals b.Id
                        select new PurchDto
                        {
                            Id = a.Id,
                            ReceiptsType = a.ReceiptsType,
                            Source = a.Source,
                            Theme = a.Theme,
                            SerialNumber = a.SerialNumber,
                            Pricing = a.Pricing,
                            Enquiry = a.Enquiry,
                            Personnel = a.Personnel,
                            Markedness = a.Markedness,
                            GetProduceDtoList = new List<ProduceDto>
                            {
                                new ProduceDto
                                {
                                    ProName = b.ProName,
                                    ProCode=b.ProCode,
                                    SpecType=b.SpecType,
                                    Unit=b.Unit,
                                    ProNumber=b.ProNumber,
                                    ProPrice=b.ProPrice,
                                    ProTaxrate=b.ProTaxrate,
                                    BillType=b.BillType,
                                    ProDiscount=b.ProDiscount,
                                    ProDiscountunit= b.ProDiscountunit,
                                    ProUnitprice=b.ProUnitprice,
                                    ProIncludingtax=b.ProIncludingtax,
                                    ProUntaxedamount=b.ProUntaxedamount,
                                    ProTheamount=b.ProTheamount,
                                    ProSumprice=b.ProSumprice,
                                    ProDeliverydate = b.ProDeliverydate,
                                    ProRemark = b.ProRemark,
                                }

                            }

                        }).ToList();

            var query = (await _repository1.GetQueryableAsync());
            var requi = (await _repository.GetQueryableAsync());
            //单据主题
            query = query.WhereIf(!string.IsNullOrWhiteSpace(input.ProName), a => a.ProName.Contains(input.ProName));

            //单价编号
            requi = requi.WhereIf(!string.IsNullOrWhiteSpace(input.SerialNumber), a => a.SerialNumber.Contains(input.SerialNumber));

            //关联项目
            requi = requi.WhereIf(!string.IsNullOrWhiteSpace(input.Markedness), a => a.Markedness.Contains(input.Markedness));

            //添加人员
            requi = requi.WhereIf(!string.IsNullOrWhiteSpace(input.Personnel), a => a.Personnel.Contains(input.Personnel));

            //日期查询
            requi = requi.WhereIf(!string.IsNullOrEmpty(input.StartDate), x => x.Enquiry >= DateTime.Parse(input.StartDate));
            requi = requi.WhereIf(!string.IsNullOrEmpty(input.EndDate), x => x.Enquiry <= DateTime.Parse(input.EndDate).AddDays(1));
            var totalCount = list.Count();
            list = list.Skip(input.SkipCount).Take(input.MaxResultCount).ToList();
            return new PagedResultDto<PurchDto>(totalCount, list);
        }
        /// <summary>
        /// 连表查询显示(三表)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<AllInfo>> GetAllse(GetPurchInputDto input)
        {
            var query = (await _repository.GetQueryableAsync());
            var dstr = (await _repository2.GetQueryableAsync());
            var pro = (await _repository1.GetQueryableAsync());
            var list = (from a in await _repository.GetQueryableAsync()
                        join b in await _repository1.GetQueryableAsync() on a.Id equals b.Id
                        join c in await _repository2.GetQueryableAsync() on b.Id equals c.Id
                        select new AllInfo
                        {
                            ReceiptsType = a.ReceiptsType,
                            Source = a.Source,
                            Theme = a.Theme,
                            SerialNumber = a.SerialNumber,
                             
                            Pricing = a.Pricing,
                            Enquiry = a.Enquiry,
                            Personnel = a.Personnel,
                            Markedness = a.Markedness,
                            Remark = a.Remark,
                            ProName = b.ProName,
                            ProCode = b.ProCode,
                            SpecType = b.SpecType,
                            Unit = b.Unit,
                            
                            ProNumber = b.ProNumber,
                            ProPrice = b.ProPrice,
                            ProTaxrate = b.ProTaxrate,
                            BillType = b.BillType,
                            ProDiscount = b.ProDiscount,
                            ProDiscountunit = b.ProDiscountunit,
                            ProUnitprice = b.ProUnitprice,
                            ProIncludingtax = b.ProIncludingtax,
                            ProUntaxedamount = b.ProUntaxedamount,
                            ProTheamount = b.ProTheamount,
                            ProSumprice = b.ProSumprice,
                            ProDeliverydate = b.ProDeliverydate,
                            ProRemark = b.ProRemark,
                            DstriName = c.DstriName,
                            DstriNumber = c.DstriNumber,
                            DstriPrice = c.DstriPrice,
                            DstriTaxrate = c.DstriTaxrate,
                            DstriType = c.DstriType,
                            DstriDiscount = c.DstriDiscount,
                            Untaxedprice = c.Untaxedprice,
                            Taxincluded = c.Taxincluded,
                            Unitprice = c.Unitprice,
                            Untaxedamount = c.Untaxedamount,
                            Theamount = c.Theamount,
                            SumPrice = c.SumPrice,
                            Deliverydate = c.Deliverydate,
                             Id = c.Id,
                            DstriRemark = c.DstriRemark,
                        }).ToList();
            //单据主题
            query = query.WhereIf(!string.IsNullOrWhiteSpace(input.Theme), a => a.Theme.Contains(input.Theme));

            //单价编号
            query = query.WhereIf(!string.IsNullOrWhiteSpace(input.SerialNumber), a => a.SerialNumber.Contains(input.SerialNumber));

            //关联项目
            query = query.WhereIf(!string.IsNullOrWhiteSpace(input.Markedness), a => a.Markedness.Contains(input.Markedness));

            //添加人员
            query = query.WhereIf(!string.IsNullOrWhiteSpace(input.Personnel), a => a.Personnel.Contains(input.Personnel));
            var totalCount = list.Count();
            list = list.Skip(input.SkipCount).Take(input.MaxResultCount).ToList();
            return new PagedResultDto<AllInfo>(totalCount, list);
        }


        public async Task<PurchDto> CreateOrUpdate(CreateOrUpdatePurchDto input)
        {
            Purch result = null;
            if (!input.Id.HasValue)
            {
                input.Id = GuidGenerator.Create();
                result = await _repository.InsertAsync(ObjectMapper.Map<CreateOrUpdatePurchDto, Purch>(input));

                //创建工作流
                //await WorkFlow.CreateWorkFlow(FormName, result);
            }
            else
            {
                var data = await _repository.GetAsync(input.Id.Value);
                result = await _repository.UpdateAsync(ObjectMapper.Map(input, data));
                //检查流程状态
                // await WorkFlow.CheckFormStatus(input.Id.Value, result);
            }
            return ObjectMapper.Map<Purch, PurchDto>(result);
        }
        public async Task<PurchDto> CreateOrUpdates(CreateOrUpdatePurchDto input)
        {
            Purch result = null;
            Random random = new Random();
            if (!input.Id.HasValue)
            {
                input.Id = GuidGenerator.Create();
                Purch purchase = new Purch()
                {
                    ReceiptsType = input.ReceiptsType,
                    Source = input.Source,
                    Theme = input.Theme,
                    SerialNumber = input.SerialNumber,
                    Pricing = input.Pricing,
                    Enquiry = input.Enquiry,
                    Personnel = input.Personnel,
                    Markedness = input.Markedness,
                    Remark = input.Remark,
                };
                //await _repository.InsertAsync(purchase);
                foreach (var item in input.GetProduceDtoList)
                {
                    var distributor = new Dstributor
                    {
                        DstriName = item.DstriName,
                        DstriNumber = item.DstriNumber,
                        DstriPrice = item.DstriPrice,
                        DstriTaxrate = item.DstriTaxrate,
                        DstriType = item.DstriType,
                        DstriDiscount = item.DstriDiscount,
                        Untaxedprice = item.Untaxedprice,
                        Taxincluded = item.Taxincluded,
                        Unitprice = item.Unitprice,
                        Untaxedamount = item.Untaxedamount,
                        Theamount = item.Theamount,
                        SumPrice = item.SumPrice,
                        Deliverydate = item.Deliverydate,
                        DstriRemark = item.DstriRemark,
                    };
                    await _repository2.InsertAsync(distributor);
                }

                result = await _repository.InsertAsync(ObjectMapper.Map<CreateOrUpdatePurchDto, Purch>(input));
            }
            else
            {
                var data = await _repository.GetAsync(input.Id.Value);
                Purch purchase = new Purch()
                {
                    ReceiptsType = input.ReceiptsType,
                    Source = input.Source,
                    Theme = input.Theme,
                    SerialNumber = input.SerialNumber,
                    Pricing = input.Pricing,
                    Enquiry = input.Enquiry,
                    Personnel = input.Personnel,
                    Markedness = input.Markedness,
                    Remark = input.Remark,
                };
                purchase = await _repository.UpdateAsync(purchase);
                result = await _repository.UpdateAsync(ObjectMapper.Map(input, data));
            }
            return ObjectMapper.Map<Purch, PurchDto>(result);
        }

        public async Task Delete(List<Guid> ids)
        {
            foreach (var item in ids)
            {
                await _repository.DeleteAsync(item);
            }

        }
        #endregion
    }
}
